package com.k12.admim.interceptor;
import cn.dev33.satoken.stp.StpInterface;
import com.k12.admim.rpc.UserFeignClient;
import com.k12.admim.utils.RedisUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.List;

@Component
public class CustomRolePermsCache implements StpInterface {

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private UserFeignClient userFeignClient;
    @Override
    public List<String> getPermissionList(Object o, String s) {

        String key = "user:perms:" + o.toString();
        List<String> perms = redisUtil.lGet(key, 0, -1);
        if(CollectionUtils.isEmpty(perms)){
            List<String> permList =userFeignClient.getPermissionList(o.toString());
            if(!CollectionUtils.isEmpty(permList)){
                for (String perm : permList) {
                    redisUtil.lStrSet(key, perm);
                }
            }
            return permList;
        }
        return perms;
    }

    @Override
    public List<String> getRoleList(Object o, String s) {
        String key = "user:role:" + o.toString();
        List<String> roles = redisUtil.lGet(key, 0, -1);
        if(CollectionUtils.isEmpty(roles)){
            List<String> roleList =userFeignClient.getRoleList(o.toString());
            if(!CollectionUtils.isEmpty(roleList)){
                for (String role : roleList) {
                    redisUtil.lStrSet(key, role);
                }
            }
            return roleList;
        }
        return roles;
    }
}
